<template>
  <div id="app" class="SkAreaTable">
    <a-card>
      <sk-life-table-header
        v-bind="$attrs"
        @dataFrom="getDataFrom"
        ref="skLifeTableHeader"
      ></sk-life-table-header>
      <div class="left-circle-icon">
        <a-icon type="left-circle" @click="closeTable" style="font-size: 22px;" />
      </div>
      <div class="table-title">
        <p>{{ tableName }}总排名</p>
      </div>
      <many-bar :width="'100%'" :data="barData" :name="barName" :height="'420px'"></many-bar>
      <a-card style="margin:25px 0;" class="card-radius">
        <div class="table-title">
          <p>{{ tableName }}排名</p>
        </div>
        <a-table :columns="columns" bordered :dataSource="dataSource" rowKey="id" :pagination="false" :scroll="{x:true}" :loading="tableLoading1">
          <span slot="statisticalDate" slot-scope="text, record">
            {{ $skCommon.tableHeaderDate({dateType,startDate:text}) }}
          </span>
          <span slot="areaName" slot-scope="text, record">
            {{ text }}
          </span>
        </a-table>
      </a-card>
      <a-card class="card-radius" v-if="classId != '0'">
        <div class="table-title">
          <p>{{ className }}-{{ dateTypeName }}-进入{{tableTitle}}人数</p>
        </div>
        <a-table :columns="columns2" bordered :dataSource="dataSource" :pagination="false">
          <span slot="statisticalDate" slot-scope="text, record">
            {{ $skCommon.tableHeaderDate({dateType,startDate:text}) }}
          </span>
          <span slot="studentCount" slot-scope="text, record">
            {{ text?text + "人": ""}}
          </span>
        </a-table>
      </a-card>
    </a-card>
  </div>
</template>
<script>
import skLifeTableHeader from '@/components/skComponent/TableHeader.vue'
import manyBar from '@/components/Echarts/manyBar.vue'
import { getAction } from "@/api/manage.js";
import { filter } from 'vuedraggable';
export default {
  name: 'SkAreaTable',
  data() {
    return {
      className:"全园",
      classId:"",
      dateType:"week",
      columns2:[],
      columns: [],
      dataSource: [],
      tableLoading1:false,
      url:{
        Duration:"/management/skArea/getAreaDuration"
      },
      barName:[],
      barData:[],
      semesterId:"",
      areaName:[],
      Days:[],
    }
  },
  props: {
    tableTitle: {
      type: String,
      default: ''
    },
  },
  watch: {
    
  },
  components: {
    skLifeTableHeader,
    manyBar
  },

  filters: {},

  computed: {
    dateTypeName() {
      let name = ''
      switch (this.dateType) {
        case 'week':
          name = '本周'
          break
        case 'month':
          name = '本月'
          break
        default:
          name = '学期'
          break
      }
      return name
    },
    tableName() {
      return `${this.className}-${this.dateTypeName}-受欢迎的${this.tableTitle}`
    },
    areaType(){
      let type = "";
      switch (this.tableTitle) {
        case "室内区域":
        type = 0
          break;
        case "户外区域":
        type = 1
          break;
        default:
        type = 2
          break;
      }
      return type
    }
  },

  created() {
    this.Days = this.$skCommon.getCurrentMonthDays()
  },

  activated() {},

  mounted() {
    
  },

  methods: {
    // 获取参数
    getDataFrom(dataForm) {
      if (dataForm.semesterId == "历史学期") {
        this.semesterId = dataForm.semesterId2;
      }else{
        this.semesterId = dataForm.semesterId;
      }
      if (dataForm.dateType == "historySem") {
        this.dateType = "sem"
      }else{
        this.dateType = dataForm.dateType;
      }
      this.classId = dataForm.classId;
      this.getAreaDuration();
    },
    getAreaDuration(){
      this.tableLoading1 = true;
      this.barData = [];
      this.barName = [];
      this.areaName = [];
      this.dataSource = [];
      let params = {
        // areaType:this.areaType,
        // classId:this.classId?this.classId:null,
        timeScope:this.dateType=="sem"?this.semesterId:this.dateType,
        areaType:this.areaType,
        classId:this.classId == "0" ?null:this.classId,
      }
      let url = this.url.Duration
      getAction(url,params).then((res)=>{
        if(res.success){
          if (res.result.length > 0) {
            let sortResult = res.result.sort((a,b)=>{
              return b.duration - a.duration
            })
            let filterResult = [];
            if (this.classId == "0") {
              this.className = "全园";
              sortResult.map(item=>{
                item.newAreaName = `${item.className}-${item.areaName}`
              })
              let obj = {}
              // 过滤班级重复的区域；每个班级只保留不同的区域
              filterResult = sortResult.reduce((newArr, next) => {
                obj[next.newAreaName] ? "" : (obj[next.newAreaName] = true && newArr.push(next));
                return newArr;
              }, []);
            }else{
              this.className = res.result[0].className;
              // 去重相同的区域
              let obj = {}
              filterResult = sortResult.reduce((newArr, next) => {
                obj[next.areaName] ? "" : (obj[next.areaName] = true && newArr.push(next));
                return newArr;
              }, []);
            }
            // // 柱状图
            let barName = [],data1 = [],data2 = [],data3 = [];
            console.log(filterResult);
            filterResult.map(item=>{
              let areaName = item.areaName;
              if (this.classId == "0") {
                areaName = item.newAreaName
              }
              this.areaName.push(areaName)
              barName.push(areaName);
              data1.push(item.duration)
              data2.push(item.studentTime)
              data3.push(item.studentCount)
            })
            this.barName = barName.slice(0,10)
            this.barData.push(data1.slice(0,10),data2.slice(0,10),data3.slice(0,10))
            
            // // 表格
            this.setColumns(sortResult);
          }
        } else {
          this.$message.warning(res.message);
        }
        this.tableLoading1 = false;
      }).catch((error)=>{
        console.error(error);
      })
    },

    setColumns(data){
      this.columns = []
      this.columns2 = [];
      let date = {
        title: '日期',
        align: 'center',
        width:140,
        dataIndex: 'statisticalDate',
        scopedSlots: { customRender: 'statisticalDate' },
      }
      this.columns.push(date)
      this.columns2.push(date)
      // 合并对象
      let arrWarp = [],result = [],id=0; // 定义新的数组
      for (let item of data) { // 遍历数组
        if (!arrWarp.includes(item.statisticalDate)) { // 判断根据哪个参数
          let obj = {
            statisticalDate: item.statisticalDate,
            list: [],
            id:id ++
          }
          obj.list.push(item);
          result.push(obj);
          arrWarp.push(item.statisticalDate);
        } else {
          result[arrWarp.indexOf(item.statisticalDate)].list.push(item);
        };
      };
      let dataColumns = [],areaName = [];
      result.forEach(item=>{
        let json = {}
        json = {
          id:item.id,
          statisticalDate:item.statisticalDate
        };
        let classData = item.list.sort((a,b)=>{
          return b.duration - a.duration
        })
        classData.forEach((j,i) => {
          let newAreaName = this.classId != 0? j.areaName: j.newAreaName
          json["areaName"+ i ] = newAreaName;
          json["studentCount"+j.areaName ] = j.studentCount 
        })
        dataColumns.push(json);
      })
      this.dataSource = dataColumns.sort((a,b)=>{
        return Date.parse(a.statisticalDate) - Date.parse(b.statisticalDate)
      });
      for (let i = 0; i < 10; i++) {
        this.columns.push({
          title:  i+ 1,
          align: 'center',
          width:100,
          dataIndex: `areaName${i}`,
          scopedSlots: { customRender: 'areaName' },
        })
      }
      this.areaName.forEach(el => {
        this.columns2.push({
          title: el,
          align: 'center',
          dataIndex: `studentCount${el}`,
          customRender: function(text) {
            return text ?text  + "人":0
          }
        })
      });
      
    },
    // 关闭表格页面
    closeTable() {
      let data = {
        show: true,
        IntimacyShow:true,
      }
      this.$emit('areaTableData', data)
    }
  }
}
</script>
<style scoped lang="less">
/* @import url(); 引入css类 */
@import '~@assets/less/skReport.less';
.table-title{
  &>p{
    text-align: center;
    font-size: 20px;
  }
}
</style>
